package com.my.aspect;

import lombok.extern.log4j.Log4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * Created by Administrator on 2017/6/13.
 */
@Aspect
@Component
@Log4j
@Order(1)
public class WebLogAspect {

    ThreadLocal<Long> startTime = new ThreadLocal<>();

    @Pointcut("execution(* com.my.controller..*.*(..))")
    public void webLog(){}

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 记录下请求内容
        log.info("URL : " + request.getRequestURL().toString());
        log.info("METHOD : " + request.getMethod());
        log.info("IP : " + request.getRemoteAddr());
        log.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        log.info("ARGS : " + Arrays.toString(joinPoint.getArgs()));
        startTime.set(System.currentTimeMillis());
    }

    @Around(value = "webLog()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {

        long startTime = System.currentTimeMillis();
        Object object = proceedingJoinPoint.proceed();
        log.info("method use time :" + String.valueOf(System.currentTimeMillis()-startTime));

        return object;//返回结果，无返回 ajax error
    }

    // 声明returning时指定的类型会限制目标方法必须返回指定类型的值或没有返回值
    // 此处将returning的类型声明为Object，意味着对目标方法的返回值不加限制
    @AfterReturning(returning="returning",value = "webLog()")
    public void doAfterReturning(Object returning) {
        log.info("doAfterReturning");
    }

    @After(value = "webLog()")
    public void doAfter() throws Throwable {
        // 处理完请求，返回内容
        log.info("SPEND TIME : " + (System.currentTimeMillis() - startTime.get()));
    }
}
